package com.bianmaba.css.service.security.user;

import com.bianmaba.css.bean.entity.Role;
import com.bianmaba.css.bean.entity.User;
import com.bianmaba.css.repository.security.user.UserRepository;
import com.bianmaba.spring.security.database.core.LocalUserDetails;
import com.bianmaba.spring.supports.service.BaseService;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.encoding.Md5PasswordEncoder;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by cwx183898 on 2017/12/14.
 */
@Service
@Transactional
public class UserService extends BaseService<User, String> implements IUserService, UserDetailsService {
    private static final Log LOG = LogFactory.getLog(UserService.class);
    @Autowired
    private UserRepository repository;

    @Override
    public UserRepository getRepository() {
        return repository;
    }

    @Override
    public <S extends User> S save(S entity) {
        if (StringUtils.isEmpty(entity.getPk())) {
            String user = SecurityContextHolder.getContext().getAuthentication().getName();
            entity.setCreator(user);
        } else {
            User old = getRepository().findOne(entity.getPk());
            if (old != null && !old.getPassword().equals(entity.getPassword())) {
                String encodedPwd = new Md5PasswordEncoder().encodePassword(entity.getPassword(), null);
                entity.setPassword(encodedPwd);
            }
        }
        return super.save(entity);
    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user = repository.findByUsername(username);
        if (user != null) {
            //预加载所有用户权限
            List<Role> roles = user.getRoles();
            List<SimpleGrantedAuthority> authorities = new ArrayList<SimpleGrantedAuthority>(0);
            for (Role role : roles) {
                authorities.add(new SimpleGrantedAuthority(role.getName()));
            }
            return new LocalUserDetails(user.getPk(), user.getName(), user.getEmail(), user.getUsername(), user.getPassword(), user.getEnabled(),
                    user.getAccountExpiringDate().getTime() > System.currentTimeMillis(),
                    user.getCredentialsExpiringDate().getTime() > System.currentTimeMillis(),
                    !user.getLocked(), authorities);
        } else {
            throw new UsernameNotFoundException("User not found!");
        }
    }
}
